package problem105;

// 105. 从前序和中序遍历序列构造二叉树
//https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

class Solution {
    private int preIndex = 0;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder, inorder, 0, preorder.length-1);
    }

    public TreeNode buildTreeChild(int[] preorder, int[] inorder, int begin, int end) {
        if(begin > end) return null;
        TreeNode root = new TreeNode(preorder[preIndex]);
        int index = findIndex(inorder, preorder[preIndex], begin, end);
        preIndex++;
        root.left = buildTreeChild(preorder, inorder, begin, index-1);
        root.right = buildTreeChild(preorder, inorder, index+1, end);
        return root;
    }

    public int findIndex(int[] inorder, int target, int begin, int end) {
        for(int i = begin; i<=end; i++) {
            if(inorder[i] == target) {
                return i;
            }
        }
        return -1;
    }
}